package com.fyzk.activity.fragment;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseFragment;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.news.NewsTypeListAdapter;
import com.fyzk.activity.news.NewsCatgoryPopupWindow;
import com.fyzk.activity.news.NewsListBean;
import com.fyzk.activity.news.NewsListFragment;
import com.fyzk.activity.news.NewsTypeListBean;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.AppUtil;
import com.fyzk.utils.LogUtil;
import com.fyzk.view.HomeTopTitleView;
import com.fyzk.view.SlidingTabLayout;

import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import com.wf.domain.UrlDef;
import http.XRequestCallBack;

/**
 * Created by fanxs11 on 17/4/21.
 *
 * 新闻资讯
 */

public class NewsFragment extends BaseFragment implements NewsTypeListAdapter.OnItemClickListener {

    private static final String TAG = NewsFragment.class.getSimpleName();
    private HomeTopTitleView topTitle;
    private Animation anim;
    private static final int SHOW_PROGRESSBAR = 0x100;
    private static final int HIDE_PROGRESSBAR = 0x101;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            try{
                switch (msg.what) {
                    case SHOW_PROGRESSBAR:
                        mProgressbarContainer.setVisibility(View.VISIBLE);
                        mContent.setVisibility(View.GONE);
                        break;
                    case HIDE_PROGRESSBAR:
                        mProgressbarContainer.setVisibility(View.GONE);
                        mContent.setVisibility(View.VISIBLE);
                        break;
                    default:
                        break;
                }
            }catch (NullPointerException e){
                showToast("网络不稳定");
            }

            return false;
        }
    });
    private static List<NewsTypeListBean.CategoryBean> newsTypeInfos;
    private SlidingTabLayout mSlidingTabLayout;
    private ViewPager mViewPager;
    private FrameLayout mActionMore;
    private ImageView mActionIndicator;
    private ImageView mActionDivider;
    private Activity mActivity;
    private NewsCatgoryPopupWindow mNewsCatgoryPopupWindow;
    private LinearLayout mMainContainer;
    private TextView mCategoryHint;
    private View mProgressbarContainer;
    private View mContent;


    private View mainView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mainView = inflater.inflate(R.layout.fragment_news2, null);
        return mainView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        mContent = null;
        mProgressbarContainer = null;
        mActionIndicator = null;
        mActionDivider = null;
        mCategoryHint = null;

        if (mMainContainer != null) {
            mMainContainer.setOnTouchListener(null);
            mMainContainer.removeAllViews();
            mMainContainer = null;
        }

        if (mNewsCatgoryPopupWindow != null) {
            mNewsCatgoryPopupWindow.dismiss();
            mNewsCatgoryPopupWindow = null;
        }

        if (mActionMore != null) {
            mActionMore.setOnClickListener(null);
            mActionMore.removeAllViews();
            mActionMore = null;
        }

        if (mSlidingTabLayout != null) {
            mSlidingTabLayout.removeAllViews();
            mSlidingTabLayout = null;
        }

        if (mViewPager != null) {
            mViewPager.setAdapter(null);
            mViewPager.removeAllViews();
            mViewPager = null;
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        mActivity = activity;
    }

    private void switchNewsCategory() {
        if (mNewsCatgoryPopupWindow.isShowing()) {
            mNewsCatgoryPopupWindow.dismiss();
            mActionDivider.setVisibility(View.VISIBLE);
            mSlidingTabLayout.setVisibility(View.VISIBLE);
            mCategoryHint.setVisibility(View.GONE);
            mActionIndicator.setImageResource(R.drawable.ic_menu_arrow_down);
        } else {
            mCategoryHint.setVisibility(View.VISIBLE);
            mSlidingTabLayout.setVisibility(View.GONE);
            mNewsCatgoryPopupWindow.showAsDropDown(mActionMore);
            mActionDivider.setVisibility(View.GONE);
            mActionIndicator.setImageResource(R.drawable.ic_menu_arrow_up);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        anim = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate);
        topTitle = (HomeTopTitleView) mainView.findViewById(R.id.news_topTitle);
        topTitle.setCenterText("新闻资讯");
        topTitle.setOnTitleClickListener(this);
        topTitle.setRightVisible(View.INVISIBLE);
        topTitle.getRightImgCom().setAnimation(anim);

        mViewPager = (ViewPager) view.findViewById(R.id.news_view_pager);
        mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.news_sliding_tab_layout);

        mCategoryHint = (TextView) view.findViewById(R.id.news_category_hint);
        mActionIndicator = (ImageView) view.findViewById(R.id.action_more_indicator);
        mActionDivider = (ImageView) view.findViewById(R.id.action_more_divider);
        mActionMore = (FrameLayout) view.findViewById(R.id.action_more_tab);
        mActionMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mNewsCatgoryPopupWindow != null) {
                    switchNewsCategory();
                }
            }
        });

        if (mNewsCatgoryPopupWindow == null && (mActivity != null)) {
            mNewsCatgoryPopupWindow = new NewsCatgoryPopupWindow(mActivity);

            mNewsCatgoryPopupWindow.setTouchable(true);
            mNewsCatgoryPopupWindow.setFocusable(true);
            mNewsCatgoryPopupWindow.setOutsideTouchable(true);
            mNewsCatgoryPopupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.white)));
            mNewsCatgoryPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mActionDivider.setVisibility(View.VISIBLE);
                    mSlidingTabLayout.setVisibility(View.VISIBLE);
                    mCategoryHint.setVisibility(View.GONE);
                    mActionIndicator.setImageResource(R.drawable.ic_menu_arrow_down);
                }
            });
        }

        mProgressbarContainer = view.findViewById(R.id.progressContainer);
        mContent = view.findViewById(R.id.news_fragment_container);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        net();

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (hidden) {
            LogUtil.d("cancelPendingRequest");
//            RequestFactory.cancelPendingRequest(TAG);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();

        LogUtil.d("cancelPendingRequest");
//        RequestFactory.cancelPendingRequest(TAG);
    }

    @Override
    public void onItemClicked(View view, int position) {
        mViewPager.setCurrentItem(position);

        switchNewsCategory();
    }

    private static class NewsNavAdapter extends FragmentPagerAdapter {

        private List<Fragment> mFragments;

        public NewsNavAdapter(FragmentManager fm) {
            super(fm);

            mFragments = new ArrayList<>();
            for (int i = 0; i < newsTypeInfos.size(); i++) {
                NewsListFragment fragment = new NewsListFragment();
                Bundle bundle = new Bundle();
//                bundle.putBoolean(NewsListFragment.SHOW_BANNER, i == 0);
                bundle.putSerializable("info", newsTypeInfos.get(i));
                fragment.setArguments(bundle);
                mFragments.add(fragment);
            }
        }

        @Override
        public Fragment getItem(int i) {
            return mFragments.get(i);
        }

        @Override
        public int getCount() {
            return newsTypeInfos.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return newsTypeInfos.get(position).getName();
        }

        public void release() {
            mFragments.clear();
            mFragments = null;
        }
    }

    /**
     * 获取新闻类型列表
     */
    protected void requestNewsTypeList() {
        RequestParams params = new RequestParams(UrlDef.NEWS_URL+Commands.NEWSTYPELIST);
        params.addBodyParameter("category", "blog");
        sendRequest(HttpMethod.GET, 0, params, true);
    }

    /**
     * U粉通接口 使用json请求数据
     *
     * @param requestCode
     * @param method
     * @param params
     * @param showProgress
     */
    public void sendRequest(HttpMethod method, int requestCode, RequestParams params, final boolean showProgress) {


        if (!AppUtil.isNetworkAvailable(getActivity())) {
            AppToast.getToast().show("网络错误!");
            return;
        }

        if (showProgress) {
//			showProgressDialog();
            mHandler.sendEmptyMessage(SHOW_PROGRESSBAR);
        }

        XRequestCallBack<String> callBack = new XRequestCallBack<String>(
                requestCode) {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
//                onFailure(getRequestCode(), "网络异常");
                LogUtil.d("请求失败");
                if (showProgress) {
//					cancelProgressDialog();
                    mHandler.sendEmptyMessage(HIDE_PROGRESSBAR);
                }
            }

            @Override
            public void onSuccess(String result) {
                LogUtil.d("联网返回成功："+result);
                super.onSuccess(result);
                NewsFragment.this.onSuccess(getRequestCode(),
                        result);
                if (showProgress) {
//					cancelProgressDialog();
                    mHandler.sendEmptyMessage(HIDE_PROGRESSBAR);
                }

            }
        };

        LogUtil.v("联网请求：" + params);
        if (method == HttpMethod.POST) {
            x.http().post(params, callBack);
        } else if (method == HttpMethod.GET) {
            x.http().get(params, callBack);
        } else {
            x.http().post(params, callBack);
        }

    }


    protected void onSuccess(int requestCode, String result) {
        switch (requestCode) {
            case 0:
                NewsTypeListBean newsTypeList = JSON.parseObject(result, NewsTypeListBean.class);
                int code = newsTypeList.getCode();
                String msg = newsTypeList.getMsg();

                if (code > 0) {
                    newsTypeInfos = newsTypeList.getData();
                    mViewPager.setAdapter(new NewsNavAdapter(getChildFragmentManager()));
                    mSlidingTabLayout.setViewPager(mViewPager);

                    NewsTypeListAdapter newsCategoryAdapter = new NewsTypeListAdapter(mActivity, 0, NewsFragment.this);
                    for (NewsTypeListBean.CategoryBean info : newsTypeInfos)
                        newsCategoryAdapter.add(info); // Compatible with API level < 11
                    mNewsCatgoryPopupWindow.setAdapter(newsCategoryAdapter);
                } else {

                }
                break;
            case 1:

                NewsListBean newsList = JSON.parseObject(result, NewsListBean.class);
                if (newsList.getStatus().equals("200")) {   // 数据获取成功

//                    setList();

                } else {    // 数据获取失败

                }
                break;
            default:
                break;
        }
    }

    private void net() {
        topTitle.getRightImgCom().startAnimation(anim);
        requestNewsTypeList();
    }

    public Context getContext() {
        return getActivity();
    }

    @Override
    public void onLeftClick() {
        getActivity().finish();
    }

    @Override
    public void onCenterClick() {

    }

    @Override
    public void onRightClick() {
        net();
    }


    @Override
    public void onRight2Click() {

    }

}
